package getHardInfo

import (
	"fmt"
	"log"
	"net"
	"regexp"

	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/host"
	"github.com/shirou/gopsutil/v3/cpu"
	"github.com/shirou/gopsutil/v3/mem"
	unet "github.com/shirou/gopsutil/v3/net"
)

func I网卡收发() string {
	//返回网卡名字
	ret := "" //make(map[int]interface{})
	//fmt.Printf("ret返回值长度: %v\n", len(ret))
	// 获取网络接口的统计信息
	interfaces, err := unet.IOCounters(true)
	if err != nil {
		log.Printf("Error getting network interface statistics: %v\n", err)
		return ret
	}
	// 遍历每个网络接口并打印收发数据包数量
	var totalMax uint64 = 0
	for _, iface := range interfaces {
		talPccks := iface.PacketsSent + iface.PacketsRecv
		if talPccks > totalMax { //找出主网卡 收发最多的那个
			totalMax = talPccks
			ret = iface.Name
		}
		// log.Printf("Interface: %s\n", iface.Name)
		// log.Printf("  talPccks =: %d totalMax =: %d \n ", talPccks, totalMax)
	}
	return ret
}

func I硬件信息() map[string]interface{} {
	硬件信息dc := make(map[string]interface{})
	info, err := host.Info() //主机信息
	if err != nil {
		log.Println("Error getting host info:", err)
	} else {
		//log.Printf("主机名：%s 版本：%s\n", info.OS, info.KernelVersion)
		硬件信息dc["主机名"] = info.Hostname
		硬件信息dc["系统版本"] = info.KernelVersion
		硬件信息dc["系统名称"] = info.OS
		硬件信息dc["运行时间"] = info.Uptime
	}
	//磁盘信息
	partitions, err := disk.Partitions(true)
	if err != nil {
		log.Println("Error getting partitions:", err)
	} else {
		// 遍历每个分区
		for _, partition := range partitions {
			// fmt.Printf("Device: %s\n", partition.Device)
			//fmt.Printf("Mountpoint: %s\n", partition.Mountpoint)
			// fmt.Printf("Fstype: %s\n", partition.Fstype)
			// fmt.Printf("Opts: %s\n", partition.Opts)

			// 获取分区使用情况
			usage, err := disk.Usage(partition.Mountpoint)
			if err != nil {
				log.Println("Error getting usage:", err)
				continue
			}
			// fmt.Printf("Total: %v\n", usage.Total)
			// fmt.Printf("Free: %v\n", usage.Free)
			// fmt.Printf("Used: %v\n", usage.Used)
			//log.Printf("分区: %s 使用率 : %f%%\n\n", partition.Mountpoint, usage.UsedPercent)
			硬件信息dc["磁盘名称"] = partition.Mountpoint
			硬件信息dc["磁盘使用率"] = usage.UsedPercent

			break
		}
	}
	// 获取硬盘的详细信息（部分系统可能不支持）
	ioCounters, err := disk.IOCounters()
	if err != nil {
		log.Println("Error getting IO counters:", err)
	} else {
		for name, ioCounter := range ioCounters {
			//log.Printf("Device: %s\n", name)
			// log.Printf("ReadCount: %d\n", ioCounter.ReadCount)
			// log.Printf("WriteCount: %d\n", ioCounter.WriteCount)
			// log.Printf("ReadBytes: %d\n", ioCounter.ReadBytes)
			// log.Printf("WriteBytes: %d\n", ioCounter.WriteBytes)
			// log.Printf("ReadTime: %d\n", ioCounter.ReadTime)
			// log.Printf("WriteTime: %d\n\n", ioCounter.WriteTime)
			硬件信息dc["主盘名称"] = name
			硬件信息dc["主盘读时间"] = ioCounter.ReadTime
			硬件信息dc["主盘写时间"] = ioCounter.WriteTime
			break
		}
	}

	// 获取 CPU 信息
	cpuInfo, err := cpu.Info()
	if err != nil {
		//log.Printf("Error getting CPU info: %v\n", err)
		return 硬件信息dc
	}

	for _, ci := range cpuInfo {
		//log.Printf("  CPU: %d, Cores: %d, Model: %s, Speed: %.2f GHz\n", ci.CPU, ci.Cores, ci.ModelName, ci.Mhz/1000)
		硬件信息dc["处理器核数"] = ci.Cores
		硬件信息dc["处理器频率"] = ci.Mhz / 1000
		硬件信息dc["处理器名称"] = ci.ModelName
		break

	}
	// 获取内存信息
	virtualMem, err := mem.VirtualMemory()
	if err != nil {
		//log.Printf("Error getting memory info: %v\n", err)
		return 硬件信息dc
	}
	硬件信息dc["内存大小"] = float64(virtualMem.Total) / (1024 * 1024 * 1024)
	硬件信息dc["内存空闲"] = float64(virtualMem.Free) / (1024 * 1024 * 1024)
	硬件信息dc["内存使用"] = float64(virtualMem.Used) / (1024 * 1024 * 1024)

	// log.Printf("\nMemory Info:\n  Total: %.2f GB, Free: %.2f GB, Used: %.2f GB\n",
	// 	float64(virtualMem.Total)/(1024*1024*1024),
	// 	float64(virtualMem.Free)/(1024*1024*1024),
	// 	float64(virtualMem.Used)/(1024*1024*1024))

	// 获取网络接口信息
	interfaces, err := net.Interfaces()
	if err != nil {
		log.Printf("Error getting network interfaces: %v\n", err)
		return 硬件信息dc
	}
	// log.Println("\nNetwork Interfaces:")

	var 主网卡名字 string = I网卡收发()
	for _, iface := range interfaces {
		//主网卡
		if 主网卡名字 == iface.Name {
			硬件信息dc["网卡名称"] = iface.Name
			硬件信息dc["网卡地址"] = fmt.Sprintf("%s", iface.HardwareAddr)

			// 定义一个正则表达式，用于查找 "Hello"
			regex := regexp.MustCompile(":")
			硬件信息dc["网卡地址"] = regex.ReplaceAllString(硬件信息dc["网卡地址"].(string), "-")
			//log.Printf("  Name: %s, MAC: %s\n", iface.Name, iface.HardwareAddr)

			// 获取接口的地址列表
			addrs, err := iface.Addrs()
			if err != nil {
				log.Println("Error getting addresses for interface", iface.Name, ":", err)
			}
			for _, addr := range addrs {
				// 解析地址
				var ip net.IP
				switch v := addr.(type) {
				case *net.IPNet:
					ip = v.IP
				case *net.IPAddr:
					ip = v.IP
				}
				// 检查是否是 IPv4 地址
				if ip != nil && ip.To4() != nil {
					log.Printf("Interface: %s, IPv4: %s\n", iface.Name, ip.String())
					硬件信息dc["网卡IP"] = fmt.Sprintf("%s", ip.String())
				}
			}
		}
	}

	//硬件信息dc := map[string]interface{}

	//m :=map[string]string{"type":"10","msg":"hello."}
	// mjson, _ := json.Marshal(硬件信息dc)
	// log.Printf("json 硬件信息 :%s\n", string(mjson))
	return 硬件信息dc
}

func Gip() {
	// 获取系统的所有网络接口
	interfaces, err := net.Interfaces()
	if err != nil {
		log.Println("Error getting network interfaces:", err)
		return
	}

	for _, i := range interfaces {
		// 获取接口的地址列表
		addrs, err := i.Addrs()
		if err != nil {
			log.Println("Error getting addresses for interface", i.Name, ":", err)
			continue
		}

		for _, addr := range addrs {
			// 解析地址
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}

			// 检查是否是 IPv4 地址
			if ip != nil && ip.To4() != nil {
				log.Printf("Interface: %s, IPv4: %s\n", i.Name, ip.String())
			}
		}
	}
}
